<template>
  <a-drawer
    v-model:visible="visible"
    title="应用分配"
    :body-style="{ paddingBottom: '80px' }"
    width="40%"
    @close="onClose"
  >
    <div class="app-title">请选择要绑定的应用</div>
    <a-select
      v-model:value="appid"
      placeholder="请选择要绑定的应用"
      size="middle"
      style="width: 60%"
      :field-names="{ label: 'appName', value: 'appId' }"
      :options="list"
    />

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="visible = false">
        <close-outlined /> 取消
      </a-button>
      <a-button
        type="primary"
        :loading="confirmLoading"
        @click="confirm('绑定应用成功')"
      >
        <check-outlined /> 保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance } from 'vue'
import { API_URL_MCH_APP, API_URL_MCH_STORE_LIST, req } from '@/api/manage'
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

const props = defineProps({
  callbackFunc: { type: Function, default: () => {} },
})
const visible: any = ref(false)
const list: any = ref([])
const appid: any = ref(null)
const confirmLoading: any = ref(false)
const getList = () => {
  req.list(API_URL_MCH_APP, {}).then(({ records }: any) => {
    records.forEach((v) => {
      v.appName = v.appName + ` [${v.appId}]`
    })
    records.unshift({
      appName: '(空)',
      appId: '',
    })
    list.value = records
  })
}
const onClose = () => {
  visible.value = false
}
const storeInfo: any = ref({})
const open = (store: any) => {
  getList()
  storeInfo.value = store
  appid.value = store.bindAppId

  visible.value = true
}

const confirm = (tips) => {
  $infoBox.confirmDanger('确认保存应用吗？', '', () => {
    confirmLoading.value = true
    req
      .updateById(API_URL_MCH_STORE_LIST, storeInfo.value.storeId, {
        bindAppId: appid.value,
      })
      .then((res) => {
        confirmLoading.value = false
        $infoBox.message.success(tips)
        props.callbackFunc()
        onClose()
      })
  })
}
defineExpose({ open })
</script>
<style lang="less" scoped>
.app-title {
  margin-bottom: 15px;
}

.reset-app {
  padding: 5px 8px;
  margin-left: 20px;
  border-radius: 5px;
  font-size: 12px;
  color: #fff;
  background-color: tomato;
  cursor: pointer;
}
</style>
>
